package com.example.demo.concurrent;/**
 * Created by kete on 2019-05-08.
 */

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 作者：kete
 * 创建时间：2019-05-08 14:30
 * 功能描述：
 * 版本：
 */
public class MultipleThreadCountDownKit {

    private AtomicInteger counter;

    private Object notify;

    private Notify notifyListen;

    public MultipleThreadCountDownKit(int number) {

        if(number<0)
            throw new IllegalArgumentException("count<0");


        counter = new AtomicInteger(number);
        notify = new Object();
    }

    public void setNotifyListen(Notify notifyListen) {
        this.notifyListen = notifyListen;
    }

    public void countDoun(){
        if(this.counter.get()<0){
            return ;
        }

        int count = this.counter.decrementAndGet();
        if(count<0){
            throw new RuntimeException("count error");
        }

        if(count == 0){
            synchronized (notify){
                notify.notify();
            }
        }
    }

    public void await() throws InterruptedException{

        synchronized (notify){

            while (counter.get()>0){
                notify.wait();
            }
        }

        if(notifyListen!=null){
            notifyListen.notifyListen();
        }
    }


}
